var express = require('express');
var router = express.Router();

const uuid = require("uuid")

const search = require("../sql/search")
const sql = require("../sql/sql")

const tools = require("../tools/index")

// 获取数据
router.get('/', function(req, res, next) {
    const token = req.headers.token

    tools.verify(token).then(result=>{
        sql.get(search, {userId: result.userId}).then(data=>{
            res.send({
               code:1,
               title:"获取成功",
               data
            })
        })
    }).catch(err=>{
        res.send({
            code:400,
            title:"登录失效",
            data:err
        })
    })
})

// 添加数据
router.post('/add', function(req, res, next) {
    const kw = req.body.keyWord

    const token = req.headers.token

    tools.verify(token).then(result=>{
        // result.userId
        sql.add(search, {
            searchId: "searchId-" + uuid.v1(),
            keyWord: kw,
            userId: result.userId,
            time: Date.now()
        }).then(()=>{
            res.send({
                code:1,
                title:"添加成功",
                data: "NOT DATA"
            })
        })
    }).catch(err=>{
        res.send({
            code:400,
            title:"登录失效",
            data:err
        })
    })

})



// 删除数据
router.post('/del', function(req, res, next) {
    const kw = req.body.keyWord

    const token = req.headers.token

    tools.verify(token).then(result=>{
        // result.userId
        sql.remove(search, {keyWord: kw}, 0).then(()=>{
            res.send({
                code:1,
                title:"删除成功",
                data: "NOT DATA"
            })
        })
    }).catch(err=>{
        res.send({
            code:400,
            title:"登录失效",
            data:err
        })
    })

})


module.exports = router;
